package com.hm.uums.controller;

import java.math.BigInteger;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.hm.common.annotation.Function;
import com.hm.common.api.ApiResult;
import com.hm.common.api.ApiStatus;
import com.hm.common.enums.Authority;
import com.hm.common.utils.MD5Utils;
import com.hm.common.utils.StringUtils;
import com.hm.uums.service.ParmService;
import com.hm.uums.service.UserService;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;

/**
 * @author hwg
 *
 *         2020年12月18日 完成用户的增删改查功能
 */
@Api(tags = "2.用户接口")
@RestController
@RequestMapping("/user")
public class UserController extends BaseController {
	Logger logger = LoggerFactory.getLogger(UserController.class);

	@Autowired
	private UserService userService;

	@Autowired
	private ParmService parmService;

	/**
	 * 查询用户信息，此方法需要验证用户是否具备权限
	 * 
	 * @param request
	 * @return
	 */
	@ApiOperation("用户查询")
	@ApiImplicitParams({@ApiImplicitParam(name = "pageNo", value = "当前页", required = true, dataType = "Integer", paramType = "query"), @ApiImplicitParam(name = "pageSize", value = "每页大小", required = true, dataType = "Integer", paramType = "query")})
	@GetMapping("/list")
	@Function(module = "uums", code = "uums.user.view", description = "用户查询")
	public ApiResult list(HttpServletRequest request) {
		String reqId = getReqId(request);
		Map<String, Object> params = getPageParam(request);
		params.put("username", request.getParameter("username"));
		params.put("fullname", request.getParameter("fullname"));
		params.put("status", request.getParameter("status"));
		params.put("orgId", request.getParameter("orgId"));

		long count = userService.count(params);
		List<Map<String, Object>> dataList = userService.list(params);

		Map<String, Object> mData = toMapResult(dataList, count);
		return ApiResult.of(reqId, ApiStatus.STATUS_200, "查询成功", request.getRequestURI(), mData);
	}

	/**
	 * 设置用户状态，此方法需要验证用户是否具备权限
	 * 
	 * @param request
	 * @return
	 */
	@ApiOperation("设置用户状态")
	@ApiImplicitParams({@ApiImplicitParam(name = "userId", value = "用户Id", required = true, dataType = "Long", paramType = "query"), @ApiImplicitParam(name = "status", value = "用户状态", required = true, dataType = "Integer", paramType = "query")})
	@PutMapping("/status")
	@Function(module = "uums", code = "uums.user.edit", description = "设置用户状态")
	public ApiResult editUserStatus(HttpServletRequest request) {
		String reqId = getReqId(request);

		String userId = request.getParameter("userId");
		String status = request.getParameter("status");

		if (StringUtils.isEmpty(userId)) {
			return ApiResult.of(reqId, ApiStatus.STATUS_800, "缺少用户Id", request.getRequestURI(), null);
		}

		if (StringUtils.isEmpty(status)) {
			return ApiResult.of(reqId, ApiStatus.STATUS_800, "缺少用户状态（status）", request.getRequestURI(), null);
		}

		userService.editUserStatus(new BigInteger(userId), Integer.parseInt(status));
		return ApiResult.of(reqId, ApiStatus.STATUS_200, "设置用户状态成功", request.getRequestURI(), null);
	}

	/**
	 * 删除用户，此方法需要验证用户是否具备权限
	 * 
	 * @param request
	 * @param userId
	 * @return
	 */
	@ApiOperation("删除用户")
	@ApiImplicitParams({@ApiImplicitParam(name = "userId", value = "用户Id", required = true, dataType = "Long", paramType = "path")})
	@DeleteMapping("/{userId}")
	@Function(module = "uums", code = "uums.user.del", description = "删除用户")
	public ApiResult delUser(HttpServletRequest request, @PathVariable(required = false) BigInteger userId) {
		String reqId = getReqId(request);
		if (StringUtils.isEmpty(userId)) {
			return ApiResult.of(reqId, ApiStatus.STATUS_800, "缺少用户Id", request.getRequestURI(), null);
		}
		userService.delUser(userId);
		return ApiResult.of(reqId, ApiStatus.STATUS_200, "删除用户成功", request.getRequestURI(), null);
	}

	/**
	 * 把新增、修改提交的用户信息封装到Map中
	 * 
	 * @param request
	 * @return
	 */
	private Map<String, Object> parseUser(HttpServletRequest request) {
		String userId = request.getParameter("userId");
		String username = request.getParameter("username");
		String fullname = request.getParameter("fullname");
		String[] orgIds = request.getParameterValues("orgId");
		String[] roleIds = request.getParameterValues("roleId");
		String mobilenumber = request.getParameter("mobilenumber");
		String officephone = request.getParameter("officephone");
		String email = request.getParameter("email");
		String desc = request.getParameter("desc");

		Set<BigInteger> orgSet = new HashSet<BigInteger>();
		for (String orgId : orgIds) {
			orgSet.add(new BigInteger(orgId));
		}

		Set<BigInteger> roleSet = new HashSet<BigInteger>();
		for (String roleId : roleIds) {
			roleSet.add(new BigInteger(roleId));
		}

		Map<String, Object> dMap = new HashMap<String, Object>();
		dMap.put("userId", StringUtils.isEmpty(userId) ? null : new BigInteger(userId));
		dMap.put("username", username);
		dMap.put("fullname", fullname);
		dMap.put("mobilenumber", mobilenumber);
		dMap.put("officephone", officephone);
		dMap.put("email", email);
		dMap.put("desc", desc);

		dMap.put("orgSet", orgSet);
		dMap.put("roleSet", roleSet);
		return dMap;
	}

	/**
	 * 获取用户，此方法需要验证用户是否具备权限
	 * 
	 * @param request
	 * @param userId
	 * @return
	 */
	@ApiOperation("获取用户")
	@GetMapping("/{userId}")
	@Function(module = "uums", code = "uums.user.view", description = "获取用户")
	public ApiResult getUser(HttpServletRequest request, @PathVariable(required = false) BigInteger userId) {
		String reqId = getReqId(request);
		if (StringUtils.isEmpty(userId)) {
			return ApiResult.of(reqId, ApiStatus.STATUS_800, "用户Id不能为空", request.getRequestURI(), null);
		}
		Map<String, Object> dMap = userService.getUser(userId);

		List<Map<String, Object>> orgList = userService.getOrgByUser(userId);
		List<Map<String, Object>> roleList = userService.getRoleByUser(userId);

		dMap.put("orgList", orgList);
		dMap.put("roleList", roleList);

		return ApiResult.of(reqId, ApiStatus.STATUS_200, "成功", request.getRequestURI(), dMap);
	}

	@ApiOperation("新增用户")
	@PostMapping
	@Function(module = "uums", code = "uums.user.add", description = "新增用户")
	public ApiResult addUser(HttpServletRequest request) {
		String reqId = getReqId(request);

		Map<String, Object> dMap = parseUser(request);

		if (StringUtils.isEmpty(dMap.get("username"))) {
			return ApiResult.of(reqId, ApiStatus.STATUS_800, "登录名不能为空", request.getRequestURI(), null);
		}

		if (StringUtils.isEmpty((Set) dMap.get("orgSet"))) {
			return ApiResult.of(reqId, ApiStatus.STATUS_800, "部门不能为空", request.getRequestURI(), null);
		}

		if (StringUtils.isEmpty((Set) dMap.get("roleSet"))) {
			return ApiResult.of(reqId, ApiStatus.STATUS_800, "角色不能为空", request.getRequestURI(), null);
		}

		Map<String, Object> configMap = parmService.getParmByKey("uums-defualt-password");

		if (StringUtils.isEmpty(configMap) || StringUtils.isEmpty(configMap.get("parmValue"))) {
			return ApiResult.of(reqId, ApiStatus.STATUS_1200, request.getRequestURI());
		}

		dMap.put("password", MD5Utils.encode((String) configMap.get("parmValue")));//设置默认密码

		userService.addUser(dMap);
		return ApiResult.of(reqId, ApiStatus.STATUS_200, "新增成功", request.getRequestURI(), null);
	}

	@ApiOperation("编辑用户")
	@PutMapping
	@Function(module = "uums", code = "uums.user.edit", description = "编辑用户")
	public ApiResult editUser(HttpServletRequest request) {
		String reqId = getReqId(request);
		Map<String, Object> dMap = parseUser(request);
		if (StringUtils.isEmpty(dMap.get("userId"))) {
			return ApiResult.of(reqId, ApiStatus.STATUS_800, "用户Id不能为空", request.getRequestURI(), null);
		}

		if (StringUtils.isEmpty(dMap.get("username"))) {
			return ApiResult.of(reqId, ApiStatus.STATUS_800, "登录名不能为空", request.getRequestURI(), null);
		}

		if (StringUtils.isEmpty((Set) dMap.get("orgSet"))) {
			return ApiResult.of(reqId, ApiStatus.STATUS_800, "部门不能为空", request.getRequestURI(), null);
		}

		if (StringUtils.isEmpty((Set) dMap.get("roleSet"))) {
			return ApiResult.of(reqId, ApiStatus.STATUS_800, "角色不能为空", request.getRequestURI(), null);
		}

		userService.editUser(dMap);
		return ApiResult.of(reqId, ApiStatus.STATUS_200, "修改成功", request.getRequestURI(), null);
	}

	@ApiOperation("修改密码")
	@PutMapping("modify/password")
	@Function(module = "uums", code = "uums.user.modify.password", description = "修改密码", authority = Authority.REQUIRE_LOGIN)
	public ApiResult modifyPassword(HttpServletRequest request) {
		String reqId = getReqId(request);
		String userIdStr = request.getParameter("userId");
		String oldPassword = request.getParameter("oldPassword");
		String newPassword = request.getParameter("newPassword");

		if (StringUtils.isEmpty(userIdStr)) {
			return ApiResult.of(reqId, ApiStatus.STATUS_800, "用户Id不能为空", request.getRequestURI(), null);
		}

		if (StringUtils.isEmpty(oldPassword)) {
			return ApiResult.of(reqId, ApiStatus.STATUS_800, "原密码不能为空", request.getRequestURI(), null);
		}

		if (StringUtils.isEmpty(newPassword)) {
			return ApiResult.of(reqId, ApiStatus.STATUS_800, "新密码不能为空", request.getRequestURI(), null);
		}

		BigInteger userId = new BigInteger(userIdStr);
		if (!userService.verifyPassword(userId, MD5Utils.encode(oldPassword))) {
			return ApiResult.of(reqId, ApiStatus.STATUS_1201, request.getRequestURI());
		}
		userService.modifyPassword(userId, MD5Utils.encode(newPassword));
		return ApiResult.of(reqId, ApiStatus.STATUS_200, "修改成功", request.getRequestURI(), null);
	}

	@ApiOperation("重置密码")
	@PutMapping("reset/password")
	@Function(module = "uums", code = "uums.user.reset.password", description = "重置密码")
	public ApiResult resetPassword(HttpServletRequest request) {
		String reqId = getReqId(request);
		String userId = request.getParameter("userId");

		if (StringUtils.isEmpty(userId)) {
			return ApiResult.of(reqId, ApiStatus.STATUS_800, "用户Id不能为空", request.getRequestURI(), null);
		}

		Map<String, Object> configMap = parmService.getParmByKey("uums-defualt-password");

		if (StringUtils.isEmpty(configMap) || StringUtils.isEmpty(configMap.get("parmValue"))) {
			return ApiResult.of(reqId, ApiStatus.STATUS_1200, request.getRequestURI());
		}

		String password = MD5Utils.encode((String) configMap.get("parmValue"));
		userService.modifyPassword(new BigInteger(userId), password);
		return ApiResult.of(reqId, ApiStatus.STATUS_200, "重置成功", request.getRequestURI(), null);
	}

	@ApiOperation("获取用户明细")
	@GetMapping("/info")
	@Function(module = "uums", code = "uums.user.view", description = "获取用户明细", authority = Authority.REQUIRE_LOGIN)
	public ApiResult getUserInfo(HttpServletRequest request) {
		String reqId = getReqId(request);
		BigInteger userId = getUserId(request);
		Map<String, Object> mMap = userService.getUserInfo(userId);
		return ApiResult.of(reqId, ApiStatus.STATUS_200, request.getContextPath(), "成功", mMap);
	}

}
